package io.hepu.robotize.base;

import io.hepu.robotize.aop.RequestLimit;
import io.hepu.robotize.http.HttpResponse;
import io.hepu.robotize.page.PageRequest;
import io.hepu.robotize.page.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class BaseController<T, ID extends Serializable, S extends IBaseService<T, ID>> implements IBaseController<T, ID> {

    @Autowired(required = false)
    protected S service;

    protected S getService() {
        return service;
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    @GetMapping("/{id}")
    @Override
    public HttpResponse<T> get(@PathVariable("id") ID id) throws Exception {
        T entity = getService().findOne(id);
        return HttpResponse.when(entity != null, entity);
    }

    @PostMapping("/create")
    @Override
    public HttpResponse<T> create(@RequestBody EntityRequest<T> request) throws Exception {
        getService().insert(request.payload());
        return HttpResponse.success();
    }

    @PutMapping("/edit")
    @Override
    public HttpResponse<T> edit(@RequestBody EntityRequest<T> request) throws Exception {
        getService().update(request.payload());
        return HttpResponse.success();
    }

    @DeleteMapping("/delete/{primaryKeys}")
    @Override
    public HttpResponse<ID[]> delete(@PathVariable(value = "primaryKeys") ID[] primaryKeys) throws Exception {
        getService().delete(primaryKeys);
        return HttpResponse.success(primaryKeys);
    }

    @DeleteMapping("/delete")
    @Override
    public HttpResponse<T> delete(@RequestBody EntityRequest<T> request) throws Exception {
        getService().delete(request.payload());
        return HttpResponse.success();
    }

    @RequestLimit
    @PostMapping("/paging")
    @Override
    public HttpResponse<PageResponse<T>> paging(@RequestBody PageRequest request) {
        PageResponse<T> paginate = getService().paginate(request);
        return HttpResponse.success(paginate);
    }
}
